<?php
class ProductOrder {
	
	/**
	 * 支付后更新订单状态
	 * id:订单id
	 * transactionId:外部支付的交易id
	 * isAddLogisticsCost:是否需要将价格设置为当前价格加运费，
	 * 		微信支付中存在问题，如果支付前将运费加上，取消再支付，运费价格相当于*2，所以订单成功后设置该金额
	 */
	public static function updateOrderDone($customerId, $ids, $transactionId, 
			$isAddLogisticsCost = false) {

		Session::switchCustomer(0);
		$OrderModel = M("module_product_order");
		$userCoupon = M("module_user_coupon");
        $MallSetting = M("customer_mall_setting");
		//供应商表,新增jie
		$vendorModel = M("mivendor");
		Session::switchCustomer($customerId);
		$user = M("user");
		$idArray = explode(',', $ids);
		$vid = '';
		foreach ($idArray as $id) {
			$whereOrder["id"] = $id;
			$order = $OrderModel->where($whereOrder)->find();
			$vid = $order['vId'];
			if ($order["status"] !== order_status_notsubmit &&
				$order["status"] !== order_status_payingconfirm &&
				$order["status"] !== ORDER_STATUS_PAYING) {
				Log::write("submit upay order status is error");
				Log::write($OrderModel->getLastSql());
				return false;
			}
			Log::write('order is ' . $order["id"]);
			if ($isAddLogisticsCost&&$order['deliveryType']=='delivery') {
				$price = $order["price"] +  $order["logisticsCost"];
			} else {
				$price = $order["price"];
			}
			if($order["freebuy"]) {
				$data["status"] = order_status_paypart;
			}else if($order["orderType"]==3){
				$data["status"] = "partake";  //已参与
			}else if($order['orderType']==6){
				$data["status"] = "supported";  //已支持
			}else if($order["isActivity"]==1){
				$data["status"] = order_status_ordersign;  //已参与
			}else if($order["isTeam"]) {
				$data["status"]="teaming";
			}
			else {
				if ($order["deliveryType"] == "pickup") {
					$data["status"]  = order_status_deliveringtostore;
				} else {
					$data["status"] = order_status_delivering;
				}
			}
			if($order['userCouponId']){
				$couponInfo = $userCoupon->alias("a")
					->join("inner join wx_module_coupon b on a.couponId=b.id")
					->field("b.money")
					->where("a.id=".$order['userCouponId'])
					->find();
				$price-=$couponInfo['money'];
                $price<0?$price=0:"";
			}

			if($order['payType'] == ORDER_PAYTYPE_AINONGPAY){	//爱农支付储存银行卡信息
				$redis = new RedisAPI();
				$bankNum = $redis->get($order['serialNumber']);
				$bankAccount = $user->where(['id' => $order['uId']])->getField('bankAccount');
				$bankAccount = json_decode($bankAccount,true);
				if(!in_array($bankNum,$bankAccount['pay'])){ //银行卡信息信息去重
					$bankAccount['pay'][] = $bankNum;
					$bankAccount = json_encode($bankAccount);
					$user->where(['id' => $order['uId']])->setField('bankAccount',$bankAccount);
				}
			}
            $where['customerId']=$customerId;
            $merchantMode = $MallSetting->where($where)->getField('merchantMode');

			$data["wxTransactionId"] = $transactionId;
			$data["price"] = $price;
			$createTime = date("Y-m-d H:i:s");
			$data["updateTime"] = $createTime;
			$data["payTime"] = $createTime;
			$data['merchantMode'] = $merchantMode;

			// 采用数据锁迚行幵发控制
			//$OrderModel->execute("LOCK TABLES __TABLE__ WRITE");
			$result = $OrderModel->where($whereOrder)->save($data);
			Log::write("更新订单  ".$OrderModel->getLastSql());
		}

		/*更新成功后, 判断供应商如果需要自动同步订单, 那么提交一条任务到任务表中, 确认一次提交的订单是否在同一商城中?*/
		$vendorInfo = $vendorModel->where(['id'=>$vid])->getField('isSynchro');
		if($vendorInfo['isSynchro']){
			$arr = [];
			$arr['oids'] = trim(implode(',', $idArray), ',');
			$bool = R('TaskQueue/addTaskQueue', [$name='synchroOrderToCrm', $module='order',$interfaceName='ApplePieAction/synchroOrder',$param=json_encode($arr),$execute_plan_time=date('Y-m-d H:i:s'), $flag=true, $cId = $customerId]);
			if(!$bool){
				Log::write('jie保存同步订单任务失败');
			}
		}

		if ($result !== false) {
			// 增加产品销量
			R('Product/addProductSalesCount', array($ids));
			if ($order["module"] != NULL) {
				self::orderDoneCallback($order);
			}
		}
		if ($result) {
		    StatisTicsAction::statisOrder($idArray,$customerId);
			$params = new stdClass();
			$params->id = $ids;
			$params->userName = $order["fromUserName"];
			Module::callModule(module_handle_product, NULL, 'orderPayCallback', $params);
		}
		return $result;
	}
	
	private static function orderDoneCallback($order) {
		$module = $order["module"];
		$method = $order["method"];
		
		if (empty($module) || empty($method)) {
			Log::write("product orderDoneCallback error");
			return;
		}
		$params = new stdClass();
		$params->userName = $order["fromUserName"];
		$params->price = $order["price"];
		$params->id = $order["moduleId"];
		$params->oid=$order["id"];
		Log::write('Enter in orderDoneCallback');
		Module::callModule($module, NULL, $method, $params);
	}
	
	/**
	 * 退款后更新订单状态
	 * oid:订单id
	 * isSuccess:是否成功
	 * resultMsg:退款结果说明
	 * upayRevoke: 是否是银联支付撤销退款，拆单的简单处理，直接设置为全部退款
	 */
	public static function updateOrderRefund($oid, $refundId, $isSuccess, $resultMsg, $upayRevoke = false) {
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductOrderModel = M("module_product_order");
		$orderDetailModel = M("module_product_order_detail");
		$RefundModel = M("module_product_order_refund");
		$enrollTable = M('mibaoming_info');
		Session::switchCustomer($cid);
		
		$whereRefund["id"] = $refundId;
		if ($isSuccess) {
			$data["status"] = status_ok;
			$data["errMsg"] = '';
		} else {
			$data["status"] = status_error;
			$data["errMsg"] = $resultMsg;
		}
		$RefundModel->where($whereRefund)->save($data);	

		// 查询是否已经全额退款成功
		$whereRefundSuccess["status"] = status_ok;
		$whereRefundSuccess["oid"] = $oid;
		$refundPriceSuccess = $RefundModel->where($whereRefundSuccess)->sum("refundPrice");	
		
		$condition["id"] = $oid;
		$order = $ProductOrderModel->where($condition)->find();
		if (!$order) {
			Log::write('updateOrderRefund error: order not found :' .  $ProductOrderModel->getLastSql());
			return;
		}
		
		// 成功退款金额和订单金额相同则全额退款
		if ($upayRevoke || ($refundPriceSuccess && $refundPriceSuccess == $order["price"])) {
			$refundStatus = ORDER_STATUS_REFUND;
		} else {
			$refundStatus = ORDER_STATUS_REFUNDEDPART;
		}

        if($order['purseMoney']>0){
            $refundMoney = $RefundModel->where($whereRefund)->getField("refundPrice");
            //判断之前退款是否把rmb支付退完
            if(($refundPriceSuccess-$refundMoney)<($order["price"]-$order["purseMoney"])){
                //计算应该退钱包的金额
                $refundMoney =  $refundMoney-(($order["price"]-$order["purseMoney"])-($refundPriceSuccess-$refundMoney));
            }
            if($refundMoney>0){
                self::purseRefund($oid,$refundMoney);
            }
        }
		$award = $refundPriceSuccess/$order["price"];
		if ($isSuccess) {
			if($order['status']!="refunding"&&$refundStatus==order_status_refund){
				R('Product/revertProductInventory', array($oid));
				R('Product/deductProductSalesCount', array($oid));
			}

			if($order['status'] != ORDER_STATUS_REFUNDEDPART){
				if(($order['type'] == ORDER_TYPE_FORM) && $order['status'] == order_status_cancel){
					/*如果营销表单退款时,订单状态为已取消,则不再进行扣减积分以及扣减分成操作,分为"已确认前/已确认后"两种情况,前没进行分成操作,
			后"已取消"已经进行了扣减操作*/
				}else{
					$deductPoint = self::deductPoint($oid, $order); //扣除积分
				}
			}

			$where["id"] = $oid;
			$ProductOrderModel->where($where)->setField('status', $refundStatus);

			if($award==1){
				if(($order['type'] == ORDER_TYPE_FORM) && $order['status'] == order_status_cancel){
					/*如果营销表单退款时,订单状态为已取消,则不再进行扣减积分以及扣减分成操作,分为"已确认前/已确认后"两种情况,
					已确认前没进行分成操作,已确认后"已取消"已经进行了扣减操作*/
				}else{
					self::delVendorCut($oid);
					self::deductionCut($oid);
				}

				if($order['orderType']==6){
					self::crowdRefund($oid);
				}

				if($order['orderType']==7){
					self::enrollRefund($oid);
				}
			}
			if($order["isVirtual"]=="1") { //虚拟商品需要重置验证码为不可用
				$ProductOrderModel->query("update wx_".$cid."_module_verify_code set disabled=0 where oid=$oid");
			}
			StatisTicsAction::statisOrderDelete($oid, $refundStatus, $cid);

			$params = new stdClass();
			$params->id = $oid;
			$params->userName = $order["fromUserName"];
			Module::callModule(module_handle_product, NULL, 'SendorderNotice', $params);

		}
		Session::switchCustomer($cid);
	}

	public static function deductPoint($oid, $order)
    {
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $ProductOrderDetailModel = M('module_product_order_detail');
        Session::switchCustomer($cid);
        $pointModel = D('Point', 'Logic');

        if ($order['partnerAwardStatus'] == 1) { //已经进行过分成
            $orderDetails = $ProductOrderDetailModel->where("oid = $oid")->select();
            $userId = $order['uId'];
            $miId = $order['miUid'];
            $preMiId = $order['refereeUid'];
            $prePreMiId = $order['parentRefereeUid'];
            $recommenderId = $order['recommenderId'];
            $serialNumber = $order['serialNumber'];
            foreach ($orderDetails as $orderDetail) {
				switch($orderDetail['type']){
					case ORDER_TYPE_FORM:
						$channel = '营销订单';
						$description = '表单名称:'.$orderDetail['name'].'|操作:退款';
						$orderType = 'formOrder';
						break;
					default:
						$channel = '商品订单';
						$description = '商品名称:'.$orderDetail['name'].'|操作:退款';
						$orderType = 'order';
						break;
				}
                $arrConfig = json_decode($orderDetail['pointConfig'], true);
//			$userPointModel->startTrans();
                /*扣购买人积分*/
                if (!empty($arrConfig['buyerPoint'])) {
                    $buyerRes = $pointModel->deductPoint(
                        $userId,
                        $arrConfig['buyerPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }

                /*给注册好友积分*/
                if (!empty($arrConfig['miPoint'])) {
                    $miRes = $pointModel->deductPoint(
                        $miId,
                        $arrConfig['miPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }

                /*给注册好友推荐人积分*/
                if (!empty($arrConfig['preMiPoint'])) {
                    $preMiRes = $pointModel->deductPoint(
                        $preMiId,
                        $arrConfig['preMiPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }

                /*给注册好友推荐人的推荐人积分*/
                if (!empty($arrConfig['prePreMiPoint'])) {
                    $prePreMiRes = $pointModel->deductPoint(
                        $prePreMiId,
                        $arrConfig['prePreMiPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }

                /*给购买人的锁定人积分*/
                if (!empty($arrConfig['recommenderPoint'])) {
                    $recommenderRes = $pointModel->deductPoint(
                        $recommenderId,
                        $arrConfig['recommenderPoint'],
						$orderType,
                        $serialNumber,
						$channel,
						$description,
                        $arrConfig['pointSchId'],
                        $arrConfig['schemeName']
                    );
                }
            }
        }
        return true;
    }
	//余额退款
    public function purseRefund($id,$refundMoney){
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $ProductOrderModel = M("module_product_order");
        $purseModel = M("module_user_purse");
        $purseBillModel = M("module_user_purse_bill");
        Session::switchCustomer($cid);
        $orderInfo = $ProductOrderModel->alias("a")
            ->join("inner join wx_".$cid."_user b on a.fromUserName=b.openid")
            ->where("a.id=$id")
            ->field("a.purseMoney,a.serialNumber,b.id as userId")
            ->find();
        $userId = $orderInfo['userId'];
        $data['cid']=$cid;
        $data['userId']=$userId;
        $data['module']="order";
        $data['moduleId']=$id;
        $data['description']="订单".$orderInfo['serialNumber']."退款";
        $data['money']=$refundMoney;
        $data['type']='0';
        $data['createTime']=date("Y-m-d H:i:s");
        $purseBillModel->add($data);
        $purseInfo = $purseModel->where("userId=$userId")->find();
        $data = null;
        $data['balance'] = $purseInfo['balance']+$refundMoney;
        $data['totalConsume'] = $purseInfo['totalConsume']-$refundMoney;
        $purseModel->where("userId=$userId")->save($data);

    }
	//众筹退款修改信息
	public function crowdRefund($oid){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductOrderModel = M("module_product_order");
		$orderDetailModel = M("module_product_order_detail");
		$crowdNumber = M("module_crowdfunding_number");
		$productModel =M("module_product");
		$crowdfundingModel = M("module_product_crowdfunding");
		Session::switchCustomer($cid);
		$crowdNumber->where("oid=$oid")->setField("status",2);
		$crowdInfo = $orderDetailModel->alias("a")
			->join("inner join wx_module_product  b on a.pid = b.id ")
			->join("inner join wx_module_product_order_detail_specification c on a.id = c.did")
			->join("inner join wx_module_product_specification d on c.firstSpecificName=d.firstSpecificName and c.secSpecificName=d.secSpecificName and d.pid =a.pid")
			->join("inner join wx_module_product_crowdfunding e on d.firstSpecificId=e.specId and e.pid = a.pid")
			->field("a.count,b.crowdStatus,a.pid,b.json,e.*")
			->where("a.oid = ".$oid)
			->find();
		$price = $ProductOrderModel->where("id=$oid")->getField("price");
		$productModel->startTrans();
		if($crowdInfo['json']){
			$json = json_decode($crowdInfo['json'],true);
			$json['supportSum']-=$price;
			$json['supportPerson']-=1;
			if($json['supportSum']<$json['crowTarget']||$crowdInfo['crowdStatus']==1){
				$data['crowdStatus']=0;//众筹状态0众筹中 1成功 2 结束
			}
			$data['json']=json_encode($json);
			$productResult = $productModel->where("id=".$crowdInfo['pid'])->save($data);
			if($productResult===false){
				$productModel->rollback();
				return;
			}
		}
		$crowdData['supportPerson'] = $crowdInfo['supportPerson']-1;
		$crowdData['supportAmount'] = $crowdInfo['supportAmount']-$crowdInfo['count'];
		if($crowdInfo['restrictPerson']){
			$crowdData['surplusPerson']=$crowdInfo['surplusPerson']+1;
		}
		if($crowdInfo['restrictAmount']){
			$crowdData['surplusAmount']=$crowdInfo['surplusAmount']+$crowdInfo['count'];
		}
		$crowdResult = $crowdfundingModel->where("id=".$crowdInfo['id'])->save($crowdData);
		if($crowdResult===false){
			$productModel->rollback();
			return;
		}
		$productModel->commit();
	}

	//订单退款扣除供应商分成
	public static function delVendorCut($oid){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$ProductOrderModel = M("module_product_order");
		$accountSupply = M("account_supply_chain");
		$sqlModel = M('');
		Session::switchCustomer($cid);
		$orderInfo = $ProductOrderModel->where("id=$oid")->field("vendorAwardStatus")->find();
		if(!$orderInfo['vendorAwardStatus']||$orderInfo['vendorAwardStatus']==2){return;}
		$sqlModel->startTrans();
		$detailList = $sqlModel->table("wx_module_product_order")->alias("a")
			->join("inner join wx_module_product_order_detail b on a.id=b.oid")
			->join("wx_customer_user c on a.fromCustomerId=c.customerId and c.supplyRelation=2")
			->field("a.vendorAwardStatus,a.vId,a.supplyChainId,a.isChainOrder,c.fullName as channelName,c.id as channelId,b.*")
			->where("a.id=$oid")
			->select();
		foreach($detailList as $key=>$value){
			$vid =  $value['vId'];
			$isVendorCut = $value['isVendorCut'];

			$data['module']='orderDetail';
			$data['oId']=$oid;
			$data['vId']=$vid;
			$data['moduleId']=$value['id'];
			$data['description']=$value['name'].'退款';
			$data['money']=$isVendorCut;
			$data['type']=1;
			$data['createTime']=date("Y-m-d H:i:s");
			$data['deleted']=0;
			$result = $sqlModel->table('wx_account_vendor')->add($data);
			Log::write("扣除供应商分成失败:".$sqlModel->getLastSql());
			if ($result === false) {
				$sqlModel->rollback();
				return false;
			}else{
				unset($data['oId']);
			}
			$sql = "UPDATE wx_mivendor SET totalRevenue = totalRevenue - $isVendorCut,balance=balance-$isVendorCut WHERE id =$vid";
			$result = $sqlModel->query($sql);
			Log::write("扣除供应商余额金额:".$sqlModel->getLastSql());
			if ($result === false) {
				$sqlModel->rollback();
				return false;
			}
			if($value['isChainOrder']){
				$data['money']=$value['isChannelCut'];
				$data['supplyChainId']=$value['supplyChainId'];
				$data['channelId']=$value['channelId'];
				$data['channelName']=$value['channelName'];
				$accountResult = $accountSupply->add($data);
				Log::write("扣除供应链分成错误 ".$accountSupply->getLastSql());
				if(!$accountResult){
					$sqlModel->rollback();
					return;
				}else{
					$coins =  $value['isChannelCut'];
					$query = "UPDATE wx_supply_chain_balance SET totalRevenue = totalRevenue - $coins,balance=balance-$coins WHERE supplyChainId =".$value['supplyChainId']." and channelId=".$value['channelId'];
					$result = $sqlModel->query($query);
					Log::write("供应链成分错误 ".$sqlModel->getLastSql());
				}
				if($result===false){
					$sqlModel->rollback();
					return;
				}
			}
		}
		$ProductOrderModel->where("id=$oid")->setField("vendorAwardStatus",2);
		$sqlModel->commit();
		return true;
	}

	//订单退款 扣除所有分成的钱
	public static function deductionCut($oid){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$orderDetailModel = M("module_product_order_detail");
		$miacAdminModel = M("system_income");
		$accountSupply = M("account_supply_chain");
		$sqlModel = M('');
		Session::switchCustomer($cid);
		$sqlModel->startTrans();
		$orderInfo = $sqlModel->table("wx_module_product_order")->alias("a")
			->join("wx_quan_user b on a.qId = b.qid and a.miUid =b.uid")
			->join("wx_all_user c on c.id=a.miUid")
			->join("wx_vendor_agent e on find_in_set(a.vId,e.vendors)")
			->join("wx_customer_user f on a.fromCustomerId=f.customerId and f.supplyRelation=2")
			->where("a.id=$oid")
			->field("e.id as agentId,a.vId,a.supplyChainId,a.price,a.status,a.uId,a.refereeUid,a.qId,a.miUid,c.fullName,a.parentRefereeUid as parRefereeUid,
			b.teamId,a.isChainOrder,f.fullName as channelName,f.id as channelId,a.partnerAwardStatus")
			->find();
		if(!$orderInfo['partnerAwardStatus']||$orderInfo['partnerAwardStatus']==2){return;}
		$qid = $orderInfo['qId'];
		$miUid = $orderInfo['miUid'];
		$refereeUid = $orderInfo['refereeUid'];
		$parRefereeUid = $orderInfo['parRefereeUid'];
		$fullName = $orderInfo['fullName'];
		$userUid = $orderInfo['uId'];
		if($orderInfo["teamId"]){
			$sql = "UPDATE wx_quan_team SET totalOrder=totalOrder-1,totalSales=totalSales-".$orderInfo["price"]." WHERE id=".$orderInfo["teamId"];
			$result = $sqlModel->query($sql);
			Log::write("写入团队表有误:".$sqlModel->getLastSql());
			if($result===false){
				$sqlModel->rollback();
				return false;
			}
		}
		if($qid&&$miUid){
			$sql = "UPDATE wx_quan_user SET totalOrder=totalOrder-1,totalSales=totalSales-".$orderInfo["price"]." WHERE qid=$qid and uid=$miUid";
			$result = $sqlModel->query($sql);
			Log::write("写入quan_user表有误:".$sqlModel->getLastSql());
			if($result===false){
				$sqlModel->rollback();
				return false;
			}
		}
		$detailList = $orderDetailModel
			->where("oid = $oid")
			->select();
		foreach($detailList as $key=>$value){
			$isUserCut = $value['isUserCut'];
			$isMiUserCut = $value['isMiUserCut'];
			$isRefereeCut = $value['isRefereeCut'];
			$isParentRefereeCut = $value['isParentRefereeCut'];
			$isLordCut = $value['isLordCut'];
			$isAgentCut = $value['isAgentCut'];
			$isVendorCut = $value['isVendorCut'];
			$isPlatCut = $value['isPlatCut'];
			$vid =  $orderInfo['vId'];
			$agentId = $orderInfo['agentId'];
			$data['module']='orderDetail';
			$data['moduleId']=$value['id'];
			$data['description']=$value['name'].'退款';
			$data['type']=1;
			$data['createTime']=date("Y-m-d H:i:s");
			$data['deleted']=0;
			$data['oId']=$oid;
			//扣除代理商分成
			if($agentId){
				$data['agentId']=$agentId;
				$data['money']=$isAgentCut;
				$result = $sqlModel->table('wx_account_agent')->add($data);
				Log::write("扣除代理商分成失败:".$sqlModel->getLastSql());
				if ($result === false) {
					$sqlModel->rollback();
					return false;
				}else{
					unset($data['agentId']);
				}
				$sql = "UPDATE wx_vendor_agent SET totalRevenue = totalRevenue - $isAgentCut,balance=balance-$isAgentCut WHERE id =$agentId";
				$result = $sqlModel->query($sql);
				Log::write("扣除代理商余额金额:".$sqlModel->getLastSql());
				if ($result === false) {
					$sqlModel->rollback();
					return false;
				}
			}
			unset($data['oId']);
			//扣除供应商分成
			$data['vId']=$vid;
			if($qid && $miUid){
				//扣除密友分成
				$data['quanId']=$qid;
				$data['uId']=$miUid;
				$data['sId']=$value['sId'];
				$data['money']=$isMiUserCut;
				$data['vsistId']=$value['vsistId'];
				$data['shareFromGuid']=$value['shareFormGuid'];
				$result = $sqlModel->table('wx_miaccount_friend')->add($data);
				Log::write("扣除密友分成失败  ".$sqlModel->getLastSql());
				if($result===false){
					$sqlModel->rollback();
					return false;
				}
				$sql = "update wx_quan_user set miCoins = miCoins - $isMiUserCut,totalRevenue=totalRevenue-$isMiUserCut WHERE qid = $qid AND uid  = $miUid";
				$result = $sqlModel->query($sql);
				Log::write("扣除密友余额失败  ".$sqlModel->getLastSql());
				if($result===false){
					$sqlModel->rollback();
					return false;
				}
				//扣除主公分成
				$data['money']=$isLordCut;
				$result = $sqlModel->table('wx_miaccount_lord')->add($data);
				Log::write("扣除主公分成失败  ".$sqlModel->getLastSql());
				if($result===false){
					$sqlModel->rollback();
					return false;
				}
				$sql = "update wx_miyouquan set coins = coins - $isLordCut,totalRevenue=totalRevenue-$isLordCut WHERE id=$qid";
				$result = $sqlModel->query($sql);
				Log::write("扣除主公余额失败  ".$sqlModel->getLastSql());
				if($result===false){
					$sqlModel->rollback();
					return false;
				}
			}

			//扣除平台分成
			$data['money']=$isPlatCut;
			$result = $sqlModel->table('wx_miaccount_system')->add($data);
			Log::write("扣除平台分成失败:".$sqlModel->getLastSql());
			if ($result === false) {
				$sqlModel->rollback();
				return false;
			}
			//扣除推荐人分成
			if($refereeUid&&$isRefereeCut>0){
				$data['money']=$isRefereeCut;
				$data['uId']=$refereeUid;
				$data['description'] = $fullName."佣金分成退款";
				$result = $sqlModel->table('wx_miaccount_friend')->add($data);
				Log::write("扣除推荐人分成失败  ".$sqlModel->getLastSql());
				if($result===false){
					$sqlModel->rollback();
					return false;
				}
				$sql = "update wx_quan_user set miCoins = miCoins - $isRefereeCut,totalRevenue=totalRevenue-$isRefereeCut WHERE qid = $qid AND uid  = $refereeUid";
				$result = $sqlModel->query($sql);
				Log::write("扣除推荐人余额失败  ".$sqlModel->getLastSql());
				if($result===false){
					$sqlModel->rollback();
					return false;
				}
			}
			if($parRefereeUid&&$isParentRefereeCut>0){
				$data['money']=$isParentRefereeCut;
				$data['uId']=$parRefereeUid;
				$data['description'] = $fullName."佣金分成退款";
				$result = $sqlModel->table('wx_miaccount_friend')->add($data);
				Log::write("扣除二级推荐人分成失败  ".$sqlModel->getLastSql());
				if($result===false){
					$sqlModel->rollback();
					return false;
				}
				$sql = "update wx_quan_user set miCoins = miCoins - $isParentRefereeCut,totalRevenue=totalRevenue-$isParentRefereeCut WHERE qid = $qid AND uid  = $parRefereeUid";
				$result = $sqlModel->query($sql);
				Log::write("扣除二级推荐人余额失败  ".$sqlModel->getLastSql());
				if($result===false){
					$sqlModel->rollback();
					return false;
				}
			}

            if($isUserCut>0){
                $data['money']=$isUserCut;
                $data['uId']=$userUid;
                $data['description'] = $fullName."佣金分成退款";
                $result = $sqlModel->table('wx_miaccount_friend')->add($data);
                Log::write("扣除二级推荐人分成失败  ".$sqlModel->getLastSql());
                if($result===false){
                    $sqlModel->rollback();
                    return false;
                }
                $sql = "update wx_quan_user set miCoins = miCoins - $isUserCut,totalRevenue=totalRevenue-$isUserCut WHERE qid = $qid AND uid  = $userUid";
                $result = $sqlModel->query($sql);
                Log::write("扣除下单人余额失败  ".$sqlModel->getLastSql());
                if($result===false){
                    $sqlModel->rollback();
                    return false;
                }
            }
			$oldincome = $miacAdminModel->field('id')->find();
			$tempoid =$oldincome['id'];
			$dtime = date("Y-m-d H:i:s");
			$sql = "UPDATE wx_system_income SET income = income - $isPlatCut, updateTime = '$dtime'  WHERE id = $tempoid";
			$result = $sqlModel->query($sql);
			Log::write("扣除平台余额金额:".$sqlModel->getLastSql());
			if ($result === false) {
				$sqlModel->rollback();
				return false;
			}
		}
		$sqlModel->table("wx_module_product_order")->where("id=$oid")->setField("partnerAwardStatus",2);
		$sqlModel->commit();
		return true;
	}

	/**
	 * 报名退款成功改变状态
	 * @param $oid 订单id
	 */
	public function enrollRefund($oid){
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$enorllTable = M('mibaoming_info');
		Session::switchCustomer($cid);
		$table = new Model();
		$table->startTrans();
		$reg = '([\s\S]*)+"oid":"'.$oid.'"';
		$sql = "select * from `wx_mibaoming_info` WHERE `pay_result_str` REGEXP '".$reg."'";
		$enorll = $table->query($sql);

		if(!$enorll){
			Log::write('查询报名订单失败'.$table->getLastSql());
			return;
		}
		$bool = $enorllTable->where(array('id'=>$enorll[0]['id']))->save(array('payment_status'=>2));
		if(!$bool){
			$table->rollback();
			Log::write('修改报名状态失败:'.$enorllTable->getLastSql());
			return;
		}

		$table->commit();
	}
}






















